// 使用 CommonJS 模块系统导入
const WebSocket = require('ws');
// 创建
const wss = new WebSocket.Server({ port: 3000 }, () => {
  console.log('服务器启动在3000');
})
const state = {
  HEART: 1,
  MESSAGE: 2,
}
// 监听
wss.on('connection', (socket) => {
  console.log('客户端连接成功');

  // 给服务端发消息
  socket.on('message', (e) => {
    // socket.send(e.toString())
    // console.log(e.toString());
    // 广播式发消息(多用户)
    wss.clients.forEach(client => {  //socket对在线用户数量具有统计
      client.send(JSON.stringify({
        type: state.MESSAGE,
        message: e.toString(),
      }))
    })
  })

  // 心跳检测
  let heartInreaval = null;
  const heartCheck = () => {
    if (socket.readyState == WebSocket.OPEN) {
      socket.send(JSON.stringify({
        type: state.HEART,
        message: '心跳检测'
      }))
    } else {
      clearInterval(heartInreaval)
    }
  }
  heartInreaval = setInterval(heartCheck, 5000)
  // 客户端断开连接时清除定时器
  // socket.on('close', () => {
  //   clearInterval(heartInterval);
  // });
})
